package pers.sloera.leetcode.editor.cn;

/**
 * 二进制数转字符串
 *
 * @author sloera
 * @date 2023-03-02 21:44:29
 */
class BianryNumberToStringLcci {
    public static void main(String[] args) {
        double a = 0.0078125;
        Solution solution = new BianryNumberToStringLcci().new Solution();
        System.out.println(solution.printBin(0.625));
        System.out.println(solution.printBin(0.1));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String printBin(double num) {
            int count = 0;
            StringBuilder ret = new StringBuilder("0.");
            // double   符号位(1bit)  指数(11 bit)   尾数(52 bit)
            // 转换进制的时候，num是变大的，精度丢失会导致计算30次后最终值不为0
            // 如果没有精度丢失，且能转换成功，那最终的结果肯定是0.0
            while (count++ < 30 && num != 0) {
                num = num * 2;
                ret.append((int) num);
                num = num - (int) num;
            }
            return num == 0 ? ret.toString() : "ERROR";
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
